package com.hntx.joymusic.mediaplayer;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.utils.FileUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cmcc.media.Micphone;
import com.google.gson.JsonObject;
import com.hntx.joymusic.Constants;
import com.hntx.joymusic.HomeKeyReceiver;
import com.hntx.joymusic.R;
import com.hntx.joymusic.adapter.MyListAdapter;
import com.hntx.joymusic.bean.SocketBean;
import com.hntx.joymusic.bean.VideoBean;
import com.hntx.joymusic.bus.RxBus;
import com.hntx.joymusic.microphone.InterfaceMicInOutAction;
import com.hntx.joymusic.sytRetrofity.SytRetrofit;
import com.hntx.joymusic.util.FileToByteUtils;
import com.hntx.joymusic.util.LiveDataBus;
import com.hntx.joymusic.util.Md5Utils;
import com.hntx.joymusic.util.UploadListener;
import com.hntx.joymusic.util.upLoadUtils;
import com.hntx.joymusic.view.CenterRecyclerView;
import com.hntx.joymusic.view.ExitDialog;
import com.hntx.joymusic.view.focus.RecyclerViewSpacesItemDecoration;
import com.hntx.joymusic.yun.YunUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static android.view.Gravity.BOTTOM;
import static android.view.Gravity.CENTER;

/**
 * Created by guo on 2018/01/01
 */
public class VideoPlayerPageActivity extends AppCompatActivity implements
        SeekBar.OnSeekBarChangeListener, MPlayer.OnTimedMPTextListener,
        View.OnClickListener, MPlayer.OnVideoChangedListener, MPlayer.IMInfoListener,
        MyListAdapter.OnRightFocusChangeListener, MyListAdapter.OnRightClickListener,
        ViewTreeObserver.OnGlobalLayoutListener, InterfaceMicInOutAction {
    private SurfaceView mPlayerView;
    private MPlayer player;
    private SeekBar seekBar;
    private RelativeLayout updateProgressBar;
    private ImageButton btn_play_pause;
    private TextView musicName, tv_time_total, tv_time_current, subtitle_text,
            seek_to_time, nextName, musicAuthor;
    private RelativeLayout playerControlBottomLayout;
    private ImageView paly_btn, load_img, forwardLeft, forwardRight,
            musicImg, musicCollect, origLyrics, musicReplay, musicNext, playMode, musicList,
            xingImg, xing_bg, lyrics_img;

    private static final int HIDE = 1, SHOW = 2, FINISH = 3, ENABLE_SEEK = 4, LYRICS_IMG_HIDE = 10,
            ENABLE_PLAY = 5, SEEK_VIEW_HIDE = 9;
    private int timeout = 8000;
    private int videoDuration;

    private Timer timer;
    private TimerTask timerTask;
    private Handler mHandler = new MyHandler(this);
    private String mName = null, authName = null, nextNameStr = null, songId;

    private List<VideoBean> videoBeanList = new ArrayList<>();
    private String userId;
    private String firstUrl = null;
    private int startPosition;
    private int nextPosition = 0;

    private List<TrackBean> audioList = null;
    private int audioSelIndex = -1;
    private int PLAY_MODE = 1;//顺序播放 1，单曲循环 2,随机播放 3

    private CenterRecyclerView recycler;
    private MyListAdapter listAdapter;
    private LinearLayoutManager layoutManager;

    public final String TAG = "MediaPlayerLogs";
    private String mBaseUrl = null;
    private String lastUrl = ".mp4";

    Micphone mMic;
    AudioManager mAudioManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        preparePlaying();
    }

    private void preparePlaying() {
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        getIntentData();
    }

    private void getIntentData() {
        setContentView(R.layout.activity_myplayer);
        /**21.06.24 麦克风相关以下*/
        mMic = (Micphone) getSystemService("Micphone");
        if (null != mMic) {
            mMic.initial();
            mMic.start();
        }

        HomeKeyReceiver.setMicInOutAction(this);
        /**21.06.24 麦克风相关以上*/
        registerMsg();
        initView();
        getInit();
        initData();
        showQR();
        initPlayer();
    }

    private void showQR() {
        DisplayMetrics metric = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            getWindowManager().getDefaultDisplay().getRealMetrics(metric);
        }
        int height = metric.heightPixels; // 高度（PX）
        Observable<String> qrbase64 = SytRetrofit.getInstance().getQR(userId, height);
        if (qrbase64 != null)
            qrbase64.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(s -> showQRcode(s));
    }

    private final CompositeDisposable disposables = new CompositeDisposable();

    private void registerMsg() {
        disposables.add(RxBus.getInstance()
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object -> {
                    SocketBean bean = (SocketBean) object;
                    if ("order".equals(((SocketBean) object).getAction())) {
                        if (bean.getContent() != null && bean.getContent().size() > 0)
                            demandPlay(bean.getContent().get(0));
                    } else if ("list".equals(((SocketBean) object).getAction())) {
                        if (bean.getContent() != null && bean.getContent().size() > 0) {
                            videoBeanList.addAll(bean.getContent());
                            listAdapter.setData(videoBeanList);
                        }
                    } else if ("delete".equals(((SocketBean) object).getAction())) {
                        int pos = -1;
                        String songId = bean.getContent().get(0).getSongId();
                        for (int i = 0; i < videoBeanList.size(); i++) {
                            if (songId.equals(videoBeanList.get(i).getSongId())) pos = i;
                        }
                        if (pos == -1) return;
                        deleteSongCommit(pos);
                        videoBeanList.remove(pos);
                        isFocus = true;
                        isDel = true;
                        delPos = pos;
                        listAdapter.setData(videoBeanList);
//                    if (videoBeanList.size() == 0) {
//                        recycler.setVisibility(View.GONE);
//                    }
                    }
                }));

        disposables.add(RxBus.getInstance("playmsg")
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object -> {
//                    SocketBean bean = (SocketBean) object;
                    String action = object.toString();
                    Log.d("服务器消息：", "播放页面：" + action);
                    switch (action) {
//                        case "order":
//                            if (bean.getContent() != null && bean.getContent().size() > 0)
//                                demandPlay(bean.getContent().get(0));
//                            break;
                        case "vol_up":
//                            dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent
//                            .KEYCODE_VOLUME_UP));
                            if (mAudioManager != null) {
                                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                        AudioManager.ADJUST_RAISE, 0);
                            }
                            break;
                        case "vol_down":
//                            dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent
//                            .KEYCODE_VOLUME_DOWN));
                            if (mAudioManager != null) {
                                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                        AudioManager.ADJUST_LOWER, 0);
                            }
                            break;
                        case "mic_up":
                            int curVolume = mMic.getVolume();
                            mMic.setVolume(curVolume + 1);
                            break;
                        case "mic_down":
                            int curVolumes = mMic.getVolume();
                            mMic.setVolume(curVolumes - 1);
                            break;
                        case "ptoggle":
                            if (player != null)
                                if (player.isPlaying()) {
                                    player.onPause();
                                    pauseVisible();
                                } else {
                                    player.onResume();
                                    btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            btn_play_pause.setVisibility(View.GONE);
                                        }
                                    }, 1500);
                                }
                            break;
                        case "ctoggle":
                            switchLrics();
                            break;
                        case "reset":
                            if (player != null && player.isPlaying())
                                player.seekto(0);
                            break;
//                        case "delete":
//                            int pos = -1;
//                            String songId = bean.getContent().get(0).getSongId();
//                            for (int i = 0; i < videoBeanList.size(); i++) {
//                                if (songId.equals(videoBeanList.get(i).getSongId())) pos = i;
//                            }
//                            if (pos == -1) return;
//                            deleteSongCommit(pos);
//                            videoBeanList.remove(pos);
//                            isFocus = true;
//                            isDel = true;
//                            delPos = pos;
//                            listAdapter.setData(videoBeanList);
////                    if (videoBeanList.size() == 0) {
////                        recycler.setVisibility(View.GONE);
////                    }
//                            break;
//                        case "list":
//                            if (bean.getContent() != null && bean.getContent().size() > 0) {
//                                videoBeanList.addAll(bean.getContent());
//                                listAdapter.setData(videoBeanList);
//                            }
//                            break;
                        case "next":
                            switchMusic();
                            break;
                        case "listtop":
                            break;
                        default:
                            break;
                    }
                }));
//        LiveDataBus.getInstance().with("socketmsg").observe(this, o -> {
//            SocketBean bean = (SocketBean) o;
//            Log.d("服务器消息：", "播放页面：" + bean.getAction());
//            switch (bean.getAction()) {
//                case "order":
//                    if (bean.getContent() != null && bean.getContent().size() > 0)
//                        demandPlay(bean.getContent().get(0));
//                    break;
//                case "vol_up":
//                    if (mAudioManager != null) {
//                        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
//                        AudioManager.ADJUST_RAISE, 0);
//                    }
//                    break;
//                case "vol_down":
//                    if (mAudioManager != null) {
//                        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
//                        AudioManager.ADJUST_LOWER, 0);
//                    }
//                    break;
//                case "mic_up":
//                    int curVolume = mMic.getVolume();
//                    mMic.setVolume(curVolume + 1);
//                    break;
//                case "mic_down":
//                    int curVolumes = mMic.getVolume();
//                    mMic.setVolume(curVolumes - 1);
//                    break;
//                case "ptoggle":
//                    if (player != null)
//                        if (player.isPlaying()) {
//                            player.onPause();
//                        } else {
//                            player.onResume();
//                        }
//                    break;
//                case "ctoggle":
//                    switchLrics();
//                    break;
//                case "reset":
//                    if (player != null && player.isPlaying())
//                        player.seekto(0);
//                    break;
//                case "delete":
//                    int pos = -1;
//                    String songId = bean.getContent().get(0).getSongId();
//                    for (int i = 0; i < videoBeanList.size(); i++) {
//                        if (songId.equals(videoBeanList.get(i).getSongId())) pos = i;
//                    }
//                    if (pos == -1) return;
//                    deleteSongCommit(pos);
//                    videoBeanList.remove(pos);
//                    isFocus = true;
//                    isDel = true;
//                    delPos = pos;
//                    listAdapter.setData(videoBeanList);
////                    if (videoBeanList.size() == 0) {
////                        recycler.setVisibility(View.GONE);
////                    }
//                    break;
//                case "list":
//                    if (bean.getContent() != null && bean.getContent().size() > 0) {
//                        videoBeanList.addAll(bean.getContent());
//                        listAdapter.setData(videoBeanList);
//                    }
//                    break;
//                case "next":
//                    switchMusic();
//                    break;
//                case "listtop":
//                    break;
//                default:
//                    break;
//            }
//                dstartPlay(0, ((SocketBean) bean).getContent());
//        });
    }

    private void deleteSongCommit(int pos) {
        Observable<JsonObject> ob =
                SytRetrofit.getInstance().postDel(videoBeanList.get(pos).getSongId(), userId, "1");
        ob.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JsonObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(JsonObject jsonObject) {
                        Log.d("sss", jsonObject.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getInit() {
        videoBeanList = getIntent().getParcelableArrayListExtra("video_bean_list");
        startPosition = getIntent().getIntExtra("start_position", 0);
        firstUrl = getIntent().getStringExtra("firstUrl");
//        firstUrl ="http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8";
//      firstUrl="http://112.115.0.136:8090/202108/LSKTV/202112/20211206/90000001000000023604022153399302/90000001000000023604022153399302.m3u8?playType=vod&startProgramDate=1638952681071&expiredTime=600&checkKey=f936f5d10fd899af1f8583ab92e9fac1&userId=0010039901049500164574FF4C692042&stbNo=0010039901049500164574FF4C692042";
        userId = getIntent().getStringExtra("userId");
        if (videoBeanList != null)
            if (videoBeanList.size() > 0 && videoBeanList.size() > startPosition) {
                mName = videoBeanList.get(startPosition).getSongName();
                songId = videoBeanList.get(startPosition).getSongId();
                authName = videoBeanList.get(startPosition).getSinger();
                nextPosition = startPosition + 1;
                if (videoBeanList.size() > 1)
                    nextNameStr = videoBeanList.get(nextPosition).getSongName();
                else
                    nextNameStr = videoBeanList.get(startPosition).getSongName();
            }
    }

    private void initView() {
        lyrics_img = findViewById(R.id.lyrics_img);
        xingImg = findViewById(R.id.xing_img);
        xing_bg = findViewById(R.id.xing_bg);
        playerControlBottomLayout = findViewById(R.id.player_control_bottom_layout);
        paly_btn = findViewById(R.id.control_btn);
        seekBar = findViewById(R.id.seekBar);
        updateProgressBar = findViewById(R.id.update_progress);
        mPlayerView = findViewById(R.id.mPlayerView);
        btn_play_pause = findViewById(R.id.btn_play_pause);
        tv_time_total = findViewById(R.id.tv_time_total);
        tv_time_current = findViewById(R.id.tv_time_current);
        subtitle_text = findViewById(R.id.subtitle_text);
        load_img = findViewById(R.id.load_img);
        seek_to_time = findViewById(R.id.seek_to_time);
        seekBar.setOnSeekBarChangeListener(this);
        paly_btn.setOnClickListener(this);

        recycler = findViewById(R.id.right_recycler);
        musicName = findViewById(R.id.music_name);
        nextName = findViewById(R.id.music_next_name);
        musicImg = findViewById(R.id.music_img);
        musicAuthor = findViewById(R.id.music_author);
        forwardLeft = findViewById(R.id.forward_left);
        forwardRight = findViewById(R.id.forward_right);
        musicCollect = findViewById(R.id.music_collect);
        origLyrics = findViewById(R.id.orig_lyrics);
        musicReplay = findViewById(R.id.music_replay);
        musicNext = findViewById(R.id.music_next);
        playMode = findViewById(R.id.play_mode);
        musicList = findViewById(R.id.music_list);

        forwardLeft.setOnClickListener(this);
        forwardRight.setOnClickListener(this);
        musicCollect.setOnClickListener(this);
        origLyrics.setOnClickListener(this);
        musicReplay.setOnClickListener(this);
        musicNext.setOnClickListener(this);
        playMode.setOnClickListener(this);
        musicList.setOnClickListener(this);
    }

    void showQRcode(String xingurl) {
        if (TextUtils.isEmpty(xingurl)) return;
        byte[] decode = Base64.decode(xingurl.split(",")[1], Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        xingImg.setImageBitmap(bitmap);
        xingImg.setVisibility(View.VISIBLE);
        Glide.with(this).load(R.mipmap.qr_k_bg).into(xing_bg);
        xing_bg.setVisibility(View.VISIBLE);
    }

    void hideQRcode() {
        xingImg.setVisibility(View.GONE);
        xing_bg.setVisibility(View.GONE);
    }

    private void initData() {
        mBaseUrl = getCacheDir().getAbsolutePath() + File.separator;
        Animation translateAnimation = AnimationUtils.loadAnimation(this, R.anim.load_anim);
        if (load_img != null) {
            load_img.setAnimation(translateAnimation);
            load_img.startAnimation(translateAnimation);
        }
        listAdapter = new MyListAdapter(this);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(listAdapter);
        listAdapter.addRightFocusChangeListener(this);
        listAdapter.addRightClickListener(this);
        recycler.addItemDecoration(new RecyclerViewSpacesItemDecoration(6));
        listAdapter.setData(videoBeanList);
        recycler.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    private void initPlayer() {
        player = new MPlayer();
        player.setDisplay(mPlayerView);
        player.setOnVideoChangedListener(this);
        player.setOnTimedMPTextListener(this);
        player.setMediaInfoListener(this);
        playerOnPrepared();
        playerSetListen();
        playerSurfaceDestroyed();
        playerOnBufferUpdateListen();
        seedCompletedListen();
        if (!TextUtils.isEmpty(firstUrl)) {
            starPlayUrl(firstUrl);
        }
    }

    private void playerSurfaceDestroyed() {
        player.setiSurfaceDestroyed(() -> mHandler.removeCallbacksAndMessages(null));
    }

    private void seedCompletedListen() {
        player.setiSeekCompleted(() -> hideBottomLayout());
    }

    private void hideBottomLayout() {
        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
        }
    }

    private void playerSetListen() {
        player.setPlayListener(new IMPlayListener() {
            @Override
            public void onStart(MPlayer player) {
            }

            @Override
            public void onPause(MPlayer player) {
            }

            @Override
            public void onResume(MPlayer player) {
            }

            @Override
            public void onComplete(MPlayer player) {
                isTimerTask = true;
//                String path = MediaRecordUtils.stopMediaRecord();
//                deleteAudioFile(path);
                switchMusic();
            }

            @Override
            public void onError(String source, int what, int extra) {
                Log.d(TAG, "视频播放出错，原因：" + what + "=" + source);
            }
        });
    }

    private void deleteAudioFile(String path) {
        boolean isdelete = FileUtils.deleteFile(path);
        Log.d(TAG, "录音没用是否删除：" + isdelete);
    }

    private void hideSeekText() {
        if (seek_to_time != null && seek_to_time.getVisibility() == View.VISIBLE) {
            seek_to_time.setVisibility(View.GONE);
        }
    }

    private void hideSeekbar() {
        if (player != null) {
            if (player.isPlaying()) {
                playerControlBottomLayout.setVisibility(View.GONE);
                btn_play_pause.setVisibility(View.GONE);
                recycler.setVisibility(View.GONE);
            }
        }
    }

    private void showSeekbar() {
        playerControlBottomLayout.setVisibility(View.VISIBLE);
        if (player != null) {
            if (!player.isPlaying()) {
                btn_play_pause.setVisibility(View.VISIBLE);
            }
        }
    }

    private void demandPlay(VideoBean bean) {
        limitOperate = false;
        String path = bean.getSongRes();
        mName = bean.getSongName();
        songId = bean.getSongId();
        videoBeanList.add(bean);
        listAdapter.setData(videoBeanList);
        if (player != null) {
            player.onDestroy();
        }
        player.setImgSurfaceGone();
        player.setDisplay(mPlayerView);
        starPlayUrl(path);
    }

    private void switchMusic() {

        if (videoBeanList != null && videoBeanList.size() > 0) {
            limitOperate = false;
            int nextp = nextPosition;
            if (PLAY_MODE == 1) {
                nextPosition++;
                if (nextPosition >= videoBeanList.size()) {
                    nextPosition = 0;
                }
                startPosition = nextp;
            } else if (PLAY_MODE == 3) {
                nextPosition = new Random().nextInt(videoBeanList.size());
                startPosition = nextp;
            } else {
                nextPosition = startPosition;
            }
            if (videoBeanList.size() == 1) {
                startPosition = 0;
                nextPosition = 0;
            }
            String path = videoBeanList.get(startPosition).getSongRes();
            //改为测试地址
//            String path = pathi + videoBeanList.get(0).getSongRes();
            mName = videoBeanList.get(startPosition).getSongName();
            songId = videoBeanList.get(startPosition).getSongId();
            nextNameStr = videoBeanList.get(nextPosition).getSongName();
            authName = videoBeanList.get(startPosition).getSinger();
            if (player != null) {
                player.onDestroy();
                player.setImgSurfaceGone();
                player.setDisplay(mPlayerView);
                starPlayUrl(path);
            }
        }else {
            limitOperate = true;
        }
    }

    private void starPlayUrl(String mUrl) {
        if (!TextUtils.isEmpty(mUrl)) {
            if (mUrl.length() > 0) {
                try {
//                    String ss = "file:////sdcard/7000948.ts";

                    player.setSource(mUrl);
//                    player.setSource(ss);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void encapsulatedOrbit(MediaPlayer.TrackInfo[] mtInfo) {
        audioList = new ArrayList<>();
        if (mtInfo != null && mtInfo.length > 0) {
            for (int i = 0; i < mtInfo.length; i++) {
                MediaPlayer.TrackInfo info = mtInfo[i];
                if (null == info) continue;
                if (info.getTrackType() == MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_AUDIO) {
                    TrackBean tb = new TrackBean();
                    tb.setIndex(i);
                    tb.setAudioName(info.getLanguage());
                    audioList.add(tb);
                }
            }
            try {
                if (!(audioList.size() > 0)) {
                    origLyrics.setFocusable(false);
                    origLyrics.setImageResource(R.drawable.music_channel_sel);
                } else {
                    origLyrics.setFocusable(true);
                    player.setSelectTrack(audioList.get(0).getIndex());
                    audioSelIndex = 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if (hasFocus) {
//            limitOperate = true;
//        }
//    }

    private boolean isTimerTask = false;

    private void playerOnPrepared() {
        player.setOnPrepared(() -> {
            try {
                MediaPlayer.TrackInfo[] mtInfo = player.getTrackInfo();
                encapsulatedOrbit(mtInfo);
                isTimerTask = false;
                limitOperate = true;

                //开始录屏录音
//                MediaRecordUtils.startMediaRecord(mBaseUrl + songId);
                mHandler.sendMessageDelayed(mHandler.obtainMessage(ENABLE_SEEK), timeout);
                videoDuration = player.getDuration();
                musicName.setText(mName);
                musicAuthor.setText(authName);
                nextName.setText("下一首：" + nextNameStr);
                try {
                    if (videoBeanList.get(startPosition).getColl().equals("y")) {
                        musicCollect.setSelected(true);
                    } else {
                        musicCollect.setSelected(false);
                    }
                } catch (Exception e) {
                    Log.d(TAG, "准备里收藏报错：" + e.getMessage());
                    e.printStackTrace();
                }
                RequestOptions options = new RequestOptions()
                        .centerCrop()
                        .placeholder(R.mipmap.default_img)
                        .error(R.mipmap.default_img);
                Glide.with(this).load(videoBeanList.get(startPosition).getPic()).apply(options).into(musicImg);
                seekBar.setMax(videoDuration);
                seekBar.setProgress(player.getCurrentPosition());
                String time = StringUtils.generateTime(videoDuration);
                tv_time_current.setText("00:00");
                tv_time_total.setText(" / " + time);
                mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
                timer = new Timer();
                timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        if (isTimerTask) {
                            if (timer != null)
                                timer.cancel();
                        }
                        if (player != null && player.isPlaying()) {
                            final int currentPosition = player.getCurrentPosition();
                            seekBar.setProgress(currentPosition);
                            VideoPlayerPageActivity.this.runOnUiThread(() -> {
                                String time1 = StringUtils.generateTime(currentPosition);
                                tv_time_current.setText(time1);
                            });
                        }
                    }
                };
                timer.schedule(timerTask, 0, 100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void playerOnBufferUpdateListen() {
        player.setImPlayerBufferUpdate((percent) ->
                runOnUiThread(() -> {
                    if (videoDuration > 0) {
                        seekBar.setSecondaryProgress((int) ((percent / 100.0) * videoDuration));
                    }
                })
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.onDestroy();
            player = null;
        }
        destroyMpush();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (playIndexTimer != null) {
            playIndexTimer.cancel();
            playIndexTimer = null;
        }
        if (load_img != null) {
            load_img.clearAnimation();
        }
        if (mExitDialog != null) {
            mExitDialog.dismiss();
        }
    }

    private void destroyMpush() {
        if (disposables != null && disposables.size() > 0)
            disposables.clear();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        try {
            player.seekto(seekBar.getProgress());
            String time = StringUtils.generateTime(player.getCurrentPosition());
            tv_time_current.setText(time);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private long mExitTime;
    ExitDialog mExitDialog = null;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getAction()) {
            case KeyEvent.ACTION_DOWN:
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_ENTER:
                    case KeyEvent.KEYCODE_DPAD_CENTER:
                        if (!limitOperate) return true;
                        mHandler.sendEmptyMessage(SHOW);
                        View view = getCurrentFocus();
                        if (seek_to_time.getVisibility() == View.VISIBLE) {
                            seek_to_time.setVisibility(View.GONE);
                        }
                        if (updateProgressBar != null && updateProgressBar.getVisibility() == View.VISIBLE) {
                            updateProgressBar.setVisibility(View.GONE);
                        }
                        if (view == null || view.getId() == R.id.seekBar || view.getId() == R.id.btn_play_pause) {
                            if (player != null) {
                                if (player.isPlaying()) {
                                    player.onPause();
                                    paly_btn.setImageResource(R.drawable.player_control_pause_sel);
                                    pauseVisible();
                                } else {
                                    try {
                                        player.onResume();
                                        paly_btn.setImageResource(R.drawable.player_control_playing_sel);
                                        btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
                                        mHandler.removeCallbacksAndMessages(null);
                                        mHandler.sendEmptyMessage(HIDE);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        break;
                    case KeyEvent.KEYCODE_DPAD_RIGHT:
                        if (!limitOperate) return true;
//                        mHandler.sendEmptyMessage(SHOW);
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessage(HIDE);
                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewRight = getCurrentFocus();
                            if (focusViewRight != null)
                                if (focusViewRight.getId() == R.id.seekBar) {
                                    if (player != null) {
                                        player.seekto(player.getCurrentPosition() + 60000);
                                    }
                                    return true;
                                }
                        } else {
                            if (player != null) {
                                seekTo(player.getCurrentPosition(), 5000);
                                player.seekto(player.getCurrentPosition() + 5000);
                            }
                            return true;
                        }
                        hideBottomLayout();
                        break;
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        if (!limitOperate) return true;
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessage(HIDE);
//                        mHandler.sendEmptyMessage(SHOW);
                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewLeft = getCurrentFocus();
                            if (focusViewLeft != null)
                                if (focusViewLeft.getId() == R.id.seekBar) {
                                    if (player != null) {
                                        player.seekto(player.getCurrentPosition() - 60000);
                                    }
                                    return true;
                                }
                        } else {
                            if (player != null) {
                                seekTo(player.getCurrentPosition(), -5000);
                                player.seekto(player.getCurrentPosition() - 5000);
                            }
                            return true;
                        }
                        hideBottomLayout();
                        break;
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        boolean isflag = false;
                        if (!limitOperate) return true;
                        mHandler.sendEmptyMessage(SEEK_VIEW_HIDE);
                        mHandler.sendEmptyMessage(SHOW);
                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewDown = getCurrentFocus();
                            if (focusViewDown != null)
                                if (focusViewDown.getId() == R.id.seekBar || focusViewDown.getId() == R.id.forward_left) {
                                    paly_btn.requestFocus();
                                    isflag = true;
                                } else if (focusViewDown.getId() == R.id.item) {
                                    seekBar.requestFocus();
                                    isflag = true;
                                }
                        }
                        /**0925 去掉 改为下面*/
                        hideBottomLayout();
                        return isflag;
                    case KeyEvent.KEYCODE_DPAD_UP:
                        boolean flag = false;
                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewUp = getCurrentFocus();
                            if (focusViewUp != null)
                                if (focusViewUp.getId() == R.id.control_btn) {
                                    seekBar.requestFocus();
                                    flag = true;
                                }
                        } else {
                            mHandler.sendEmptyMessage(SEEK_VIEW_HIDE);
                            mHandler.sendEmptyMessage(SHOW);
                        }
                        hideBottomLayout();
                        return flag;
                    case KeyEvent.KEYCODE_BACK:
                        if (recycler.getVisibility() == View.VISIBLE) {
                            recycler.setVisibility(View.GONE);
                            return true;
                        }
                        if ((System.currentTimeMillis() - mExitTime) > 2000) {
                            Toast.makeText(this, "再按一次退出播放", Toast.LENGTH_SHORT).show();
                            mExitTime = System.currentTimeMillis();
                            return true;
                        } else {
                            exit();
//                            if (player != null) {
//                                player.onPause();
//                            }
//                            Log.d(TAG, "退出的地方，记录一下");
////                            String path2 = MediaRecordUtils.stopMediaRecord();
//                            if (mExitDialog == null)
//                                mExitDialog = new ExitDialog(this, new ExitDialog
//                                .onBtnClickListener() {
//                                    @Override
//                                    public void onSure(String path) {
//                                        exit();
//                                    }
//
//                                    @Override
//                                    public void onExit() {
//                                        if (player != null) {
//                                            player.onResume();
//                                        }
//                                    }
//                                }, null, null, null, null);
////                            mExitDialog.setPath(path2);
//                            mExitDialog.show();
//                            Log.d(TAG, "退出的地方，记录一下 展示");


//                            Log.d(TAG, "退出的地方，记录一下");
//                            String path2 = MediaRecordUtils.stopMediaRecord();
//                            if (mExitDialog == null)
//                                mExitDialog = new ExitDialog(this, new ExitDialog
//                                .onBtnClickListener() {
//                                    @Override
//                                    public void onSure(String path) {
////                                        Intent intent = new Intent(VideoPlayerPageActivity
// .this, AudioRecordAc.class);
////                                        intent.putExtra("path", path);
////                                        startActivity(intent);
//                                        exit();
//                                    }
//
//                                    @Override
//                                    public void onExit() {
////                                        startUpdateFile(path2);
//                                        createUploadUrl(path2);
////                                        exit();
//                                    }
//                                }, "退出", "上传录音", null, null);
//                            mExitDialog.setPath(path2);
//                            mExitDialog.show();
//                            Log.d(TAG, "退出的地方，记录一下 展示");
                        }
                        return true;
                    case KeyEvent.KEYCODE_HOME:
                        return true;
                }
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    private void seekTo(int currentTime, int seekTime) {
        StringBuilder sb = new StringBuilder();
        sb.append("(").append(StringUtils.generateTime(currentTime)).append(')');
        if (seekTime > 0) {
            sb.append("+" + seekTime / 1000f);
        } else {
            sb.append(seekTime / 1000f);
        }
        seek_to_time.setText(sb.toString());
        if (seek_to_time.getVisibility() != View.VISIBLE) {
            seek_to_time.setVisibility(View.VISIBLE);
        }
        mHandler.removeMessages(SEEK_VIEW_HIDE);
        mHandler.sendEmptyMessageDelayed(SEEK_VIEW_HIDE, 2000);
    }

    public void pauseVisible() {
        btn_play_pause.setImageResource(R.mipmap.mediacontroller_play);
        btn_play_pause.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.control_btn:
                try {
                    if (updateProgressBar != null && updateProgressBar.getVisibility() == View.VISIBLE) {
                        updateProgressBar.setVisibility(View.GONE);
                    }
                    if (player.isPlaying()) {
                        player.onPause();
                        paly_btn.setImageResource(R.drawable.player_control_pause_sel);
                        btn_play_pause.setImageResource(R.mipmap.mediacontroller_play);
                        btn_play_pause.setVisibility(View.VISIBLE);
                    } else {
                        player.onResume();
                        paly_btn.setImageResource(R.drawable.player_control_playing_sel);
                        btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessage(HIDE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.forward_left:
                //快退处理
                if (player != null) {
                    player.seekto(player.getCurrentPosition() - 5000);
                }
                break;
            case R.id.forward_right:
                //快进处理
                if (player != null) {
                    player.seekto(player.getCurrentPosition() + 5000);
                }
                break;
            case R.id.music_list:
                //目前不清楚功能，应该是列表选择
                if (recycler.getVisibility() == View.VISIBLE) {
                    recycler.setVisibility(View.GONE);
                } else {
                    recycler.setVisibility(View.VISIBLE);
                    isFocus = true;
                }
                break;
            case R.id.play_mode:
                //修改播放模式，当前总共三种播放模式，循环列表，单曲循环，随机列表播放<可能会出现重复播放>
                PLAY_MODE++;
                switch (PLAY_MODE) {
                    case 1:
                        playMode.setImageResource(R.drawable.play_mode_sel);
                        break;
                    case 2:
                        playMode.setImageResource(R.drawable.play_mode_sel1);
                        break;
                    case 3:
                        playMode.setImageResource(R.drawable.play_mode_sel2);
                        break;
                    default:
                        PLAY_MODE = 1;
                        playMode.setImageResource(R.drawable.play_mode_sel);
                        break;
                }
                break;
            case R.id.music_replay:
                //当前歌曲重新开始播放
                player.seekto(0);
                break;
            case R.id.music_next:
                //先判断播放模式，再根据模式切换到下一首
                switchMusic();
                break;
            case R.id.orig_lyrics:
                //麦克风选择处理
                switchLrics();
                break;
            case R.id.music_collect:
                //提交收藏接口
                if (musicCollect.isSelected()) {
                    musicCollect.setSelected(false);
                } else {
                    musicCollect.setSelected(true);
                }
                collectPost();
                break;
            default:
                break;
        }
    }

    private void switchLrics() {
        if (audioList != null && null != player)
            if (audioList.size() >= 2) {
                audioSelIndex++;
                if (audioSelIndex == 1) {
                    origLyrics.setImageResource(R.drawable.music_channel_sel1);
                    player.setSelectTrack(audioList.get(audioSelIndex).getIndex());
                    ToastUtils.showLongToast("已切换到伴唱");
//                            DialogUtils.popupWindowShow(this, R.mipmap.sta_channel_b);
                } else {
                    audioSelIndex = 0;
                    origLyrics.setImageResource(R.drawable.music_channel_sel);
                    player.setSelectTrack(audioList.get(audioSelIndex).getIndex());
                    ToastUtils.showLongToast("已切换到原唱");
//                            DialogUtils.popupWindowShow(this, R.mipmap.sta_channel0_b);
                }
            } else {
                ToastUtils.showShortToastSafe("此歌曲不支持伴唱！");
            }

    }

    private void showLricsImg(int src_img) {
        if (lyrics_img.getVisibility() != View.VISIBLE) {
            lyrics_img.setImageResource(src_img);
            lyrics_img.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(LYRICS_IMG_HIDE, 2000);
        } else {
            lyrics_img.setImageResource(src_img);
            mHandler.removeMessages(LYRICS_IMG_HIDE);
            mHandler.sendEmptyMessageDelayed(LYRICS_IMG_HIDE, 2000);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LiveDataBus.getInstance().send("main", 10001);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void OnVideoChanged(boolean flag) {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        subtitle_text.setLayoutParams(params);
        params.gravity = CENTER | BOTTOM;
        if (flag) {
            params.setMargins(0, 0, 0, 10);
        } else {
            params.setMargins(0, 0, 0, 100);
        }
    }

    @Override
    public boolean onMediaInfo(MediaPlayer mediaPlayer, int arg1, int arg2) {
        switch (arg1) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                //开始缓存，暂停播放
                updateProgressBar.setVisibility(View.VISIBLE);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                //缓存完成，继续播放
                if (player.isPlaying())
                    updateProgressBar.setVisibility(View.GONE);
                break;
            case 3000:
                if (player.isPlaying())
                    updateProgressBar.setVisibility(View.GONE);
                else
                    updateProgressBar.setVisibility(View.VISIBLE);
                break;
        }
        return true;
    }

    @Override
    public void setOnTimeMpTextListener(MediaPlayer mediaPlayer, TimedText timedText) {
        subtitle_text.setText(timedText.getText());
    }

    @Override
    public void onRightFocusChange(View view, boolean flag, int pos) {
        if (flag) {
            recycler.smoothToCenter(pos);
        }
    }

    @Override
    public void onRightClick(View view, int pos) {
        switch (view.getId()) {
            case R.id.delete_m:
                deleteSongCommit(pos);
                videoBeanList.remove(pos);
                isFocus = true;
                isDel = true;
                delPos = pos;
                listAdapter.setData(videoBeanList);
                if (videoBeanList.size() == 0) {
                    recycler.setVisibility(View.GONE);
                }
                break;
            case R.id.start_play:
                startPosition = pos;
                if (PLAY_MODE == 1) {
                    nextPosition++;
                    if (nextPosition >= videoBeanList.size()) {
                        nextPosition = 0;
                    }
                } else if (PLAY_MODE == 3) {
                    nextPosition = new Random().nextInt(videoBeanList.size());
                }
                String path = videoBeanList.get(startPosition).getSongRes();
//                String path = pathi + videoBeanList.get(startPosition).getSongRes();
                mName = videoBeanList.get(startPosition).getSongName();
                songId = videoBeanList.get(startPosition).getSongId();
                nextNameStr = videoBeanList.get(nextPosition).getSongName();
                authName = videoBeanList.get(startPosition).getSinger();
                if (player != null) {
                    player.onDestroy();
                }
                player.setImgSurfaceGone();
                player.setDisplay(mPlayerView);
                starPlayUrl(path);
                break;
        }
    }

    private boolean isFocus = false, isDel = false;
    private int delPos = 0;

    @Override
    public void onGlobalLayout() {
        if (videoBeanList.size() > 0)
            if (recycler.getVisibility() == View.VISIBLE && isFocus) {
                isFocus = false;
                if (isDel) {
                    isDel = false;
                    if (videoBeanList.size() > 0) {
                        if (videoBeanList.size() > delPos)
                            recycler.getLayoutManager().findViewByPosition(delPos).findViewById(R.id.delete_m).requestFocus();
                        else {
                            recycler.getLayoutManager().findViewByPosition(videoBeanList.size() - 1).findViewById(R.id.delete_m).requestFocus();
                        }
                    }
                } else
                    recycler.getLayoutManager().findViewByPosition(startPosition).findViewById(R.id.start_play).requestFocus();
            }
    }

    public static final int _SHOW = 1000, _UPDATE = 2000, _DISMISS = 3000;

    @Override
    public void micIn() {
        ToastUtils.showShortToast("麦克风已插入！");
    }

    @Override
    public void micOut() {
        ToastUtils.showShortToast("麦克风已被拔出！");
    }

    private class MyHandler extends Handler {
        private WeakReference<VideoPlayerPageActivity> reference;

        public MyHandler(VideoPlayerPageActivity reference) {
            this.reference = new WeakReference<VideoPlayerPageActivity>(reference);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            VideoPlayerPageActivity ac = reference.get();
            switch (msg.what) {
                case HIDE:
                    hideSeekbar();
                    break;
                case SHOW:
                    showSeekbar();
                    break;
                case FINISH:
                    LiveDataBus.getInstance().send("main", 10001);
                    finish();
                    break;
                case ENABLE_SEEK:
                    break;
                case ENABLE_PLAY:
                    try {
                        player.onResume();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case SEEK_VIEW_HIDE:
                    hideSeekText();
                    break;
                case _SHOW:
                    ac.progressShow(msg.arg1);
                    break;
                case _UPDATE:
                    ac.updateProgress(msg.arg1);
                    break;
                case _DISMISS:
                    if (ac.dialog != null) {
                        ac.dialog.dismiss();
                    }
                    exit();
                    break;
                case LYRICS_IMG_HIDE:
                    lyrics_img.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
    }


    protected void exit() {
        mHandler.removeCallbacksAndMessages(null);
        isTimerTask = true;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (player != null) {
            player.onDestroy();
            player = null;
        }
        if (authDisposable != null) {
            authDisposable.dispose();
            authDisposable = null;
        }
        LiveDataBus.getInstance().send("main", 10001);
        finish();
        overridePendingTransition(0, 0);
    }

    private boolean limitOperate = false;
    private Timer playIndexTimer;
    Disposable authDisposable;

    public void collectPost() {
        Observable<JsonObject> ob = SytRetrofit.getInstance()
                .postCollect(videoBeanList.get(startPosition).getSongId(),
                        userId, "1", "collect");
        if (ob != null)
            ob.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<JsonObject>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(JsonObject jsonObject) {
                            Log.d("sss", jsonObject.toString());
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
    }

    private void startUpdateFile(String pathname) {
        new Thread(() -> {
            File file = new File(pathname);
            if (!file.exists()) return;
            long size = file.length();
            mHandler.sendMessage(mHandler.obtainMessage(_SHOW, (int) size, 0));
            upLoadUtils.uploadfile("sopftpuser", "n0passw0rd!@#$",
                    "wwws", "", file, (current, size1)
                            -> mHandler.sendMessage(mHandler.obtainMessage(_UPDATE,
                            (int) current, 0)));
        }).start();
    }

    ProgressBar progressBar;
    AlertDialog dialog;
    TextView textView;

    public void progressShow(int max) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null, false);
        dialog = builder.setView(view).create();
        progressBar = view.findViewById(R.id.progress);
        textView = view.findViewById(R.id.update_text);
        progressBar.setMax(max);
        dialog.show();
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialogWindow.setGravity(Gravity.CENTER);
        //dialog的大小
        lp.width = 600;
        lp.height = 120;
        dialogWindow.setAttributes(lp);
    }

    public void updateProgress(int current) {
        if (progressBar != null && dialog.isShowing()) {
            if (progressBar.getMax() == current) {
                Log.d("正在上传", "上传完成");
                textView.setText("上传完成");
//                mHandler.sendMessageDelayed(mHandler.obtainMessage(_DISMISS), 1000);
            } else {
                progressBar.setProgress(current);
            }
        }
    }

    void createUploadUrl(String upAudioNamePath) {
        String path = "https://api-b.cloud.189.cn/api/getCorpPutUploadURL.action";
        path = YunUtils.getPath(path);
        String date = YunUtils.getDateStr();
        String sign = YunUtils.sign(Constants.yunToken, "POST", path, date);

        Observable.create(emitter -> YunUtils.putCorpFileUrl(Constants.yunToken, sign, date,
                Constants.yunAppkey, Constants.corpId, upbean -> {
                    String uploadUrl = upbean.getFileUploadUrl();
                    emitter.onNext(uploadUrl);
                })).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap((Function<Object, ObservableSource<JsonObject>>) o -> {
                    File audioFile = new File(upAudioNamePath);
                    String date1 = YunUtils.getDateStr();
                    String url = YunUtils.getPath(o.toString());
                    String signature = YunUtils.sign(Constants.yunToken, "POST", url, date1);
                    Map<String, String> map = new HashMap();
                    map.put("AccessToken", Constants.yunToken);
                    map.put("Signature", signature);
                    map.put("Date", date1);
                    map.put("CorpId", Constants.corpId);
                    map.put("ParentId", Constants.uploadFileId);
                    map.put("FileName", audioFile.getName());
                    map.put("Size", audioFile.length() + "");
                    map.put("Md5", Md5Utils.getMd5(upAudioNamePath));
                    map.put("OperType", "3");
                    map.put("BaseFileId", "");
                    map.put("FileSource", "1");
                    mHandler.sendMessage(mHandler.obtainMessage(_SHOW, (int) audioFile.length(),
                            0));
                    byte[] btes = FileToByteUtils.InputStreamTOByte(upAudioNamePath,
                            new UploadListener() {
                                @Override
                                public void update(long current, long size) {
                                    mHandler.sendMessage(mHandler.obtainMessage(_UPDATE,
                                            (int) current, 0));
                                }
                            });
                    return SytRetrofit.getInstance().putCorpFile(o.toString(), btes, map);
                }).subscribe(new Observer<JsonObject>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JsonObject o) {
                Log.d(TAG, "DDDDD1111" + o.toString());
                mHandler.sendMessageDelayed(mHandler.obtainMessage(_DISMISS), 1000);
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "DDDDD2222" + e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }
}